import axios from 'axios';

const getToken = (): string | undefined => {
	return undefined // from localstorage?
}

const handler401 = () => {
	console.log('401', '请重新登录')
	// remove token
	// goto login?
}

const handler402 = () => {
	console.log('402', '准备退出登录')
	// remove token
	// goto logout?
}

const handler5xx = (msg: string) => {
	console.log('5xx', msg)
}

const onRequestError = (msg: string) => {
	console.log('onRequestError', msg)
}

axios.defaults.headers.post['Content-Type'] = 'application/json'
// 配置新建一个 axios 实例
const service = axios.create({
	baseURL: import.meta.env.VITE_API_URL as any,
	timeout: 50000,
	// headers: { 'Content-Type': 'application/json' },
})

// 添加请求拦截器
service.interceptors.request.use(
	(config) => {
		// 在发送请求之前做些什么 token
		config.headers['Authorization'] = `Bearer ${getToken() || ""}`;
		return config;
	},
	(error) => {
		// 对请求错误做些什么
		return Promise.reject(error);
	}
)

// 添加响应拦截器
service.interceptors.response.use(
	(response) => {
		// 对响应数据做点什么
		const res = response.data;
		if (res.code && res.code !== 200) {
			// `token` 过期或者账号已在别处登录
			if (res.code === 401) {
				handler401()
			} else if (res.code === 402) {
				handler402()
			} else if (res.code == 500) {
				handler5xx(res.message)
			}
			return Promise.reject(service.interceptors.response);
		} else {
			return response.data;
		}
	},
	(error) => {
		// 对响应错误做点什么
		if (error.message.indexOf('timeout') != -1) {
			onRequestError('网络超时')
		} else if (error.message == 'Network Error') {
			onRequestError('网络连接错误')
		} else {
			if (error.response.data) onRequestError(error.response.statusText)
			else onRequestError('接口路径找不到')
		}
		return Promise.reject(error);
	}
)

export function get(url: string, params: object) {
	return service.request({
		url: url,
		method: 'get',
		params: params,
	});
}

export function post(url: string, params: object) {
	return service.request({
		url: url,
		method: 'post',
		data: params,
	});
}

export function put(url: string, params: object) {
	return service.request({
		url: url,
		method: 'put',
		data: params,
	});
}

export function del(url: string, params: object) {
	return service.request({
		url: url,
		method: 'delete',
		data: params,
	});
}

// 导出 axios 实例
export default service;
